package com.zwj.batch.config.test;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.NonTransientResourceException;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 块Tasklet,直到读到的数据为null时，才会停止批处理
 *
 * @author 张文接
 * @version 1.0
 * @createTime 2023-06-20 21:41:00
 */
//@Configuration
public class BatchConfig10 {
    int item = 20;
    @Resource
    private JobBuilderFactory jobBuilderFactory;
    @Resource
    private StepBuilderFactory stepBuilderFactory;

    @Bean
    public Job job() {
        return jobBuilderFactory
                .get("myJob1")
                .incrementer(new RunIdIncrementer())
                .start(myStep())
                .build();
    }

    @Bean
    public Step myStep() {
        return stepBuilderFactory
                .get("myStep")
                .chunk(10)
                .writer(myWriter())
                .processor(myProcess())
                .reader(myReader())
                .build();
    }

    @Bean
    public ItemReader<?> myReader() {
        return new ItemReader<Object>() {
            @Override
            public Object read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
                while (item > 0) {
                    item--;
                    System.err.println("执行，读取数据");
                    return "读取到的数据";
                }
                return null;
            }
        };
    }

    @Bean
    public ItemProcessor<? super Object, ?> myProcess() {
        return new ItemProcessor<Object, Object>() {
            @Override
            public Object process(Object o) throws Exception {
                System.err.println("已处理的数据为：" + o.toString());
                return "处理结果";
            }
        };
    }

    @Bean
    public ItemWriter<? super Object> myWriter() {
        return new ItemWriter<Object>() {
            @Override
            public void write(List<?> list) throws Exception {
                int count = 0;
                if (!CollectionUtils.isEmpty(list)) {
                    count = list.size();
                }
                System.err.println("已入库【" + count + "】条数据");
            }
        };
    }
}
